package com.migrate.module.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 手动获取spring管理的bean的工具类
 *
 * @author zhonghuashishan
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware
{
    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        context = applicationContext;
    }

    /**
     * 获取spring上下文
     * @return spring上下文
     */
    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * 根据bean名称获取bean
     * @param beanName bean名称
     * @return spring管理的bean
     */
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    /**
     * 根据Bean的对象获取对应得Bean
     * @param required
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> required){
        return context.getBean(required);
    }
}
